const { v4: uuidv4 } = require('uuid');

module.exports = {
  up: async (queryInterface) => {
    const now = new Date();

    // 获取系统管理菜单ID
    const [systemMenus] = await queryInterface.sequelize.query(
      `SELECT id FROM menus WHERE name = 'system' AND parent_id IS NULL LIMIT 1`
    );

    if (!systemMenus || systemMenus.length === 0) {
      console.log('❌ 未找到系统管理菜单');
      return;
    }

    const systemId = systemMenus[0].id;

    // 检查是否已存在公司管理菜单
    const [existingCompany] = await queryInterface.sequelize.query(
      `SELECT id FROM menus WHERE name = 'company' LIMIT 1`
    );

    if (existingCompany && existingCompany.length > 0) {
      console.log('✅ 组织架构菜单已存在');
      return;
    }

    const companyMenuId = uuidv4();
    const departmentMenuId = uuidv4();

    // 添加组织架构菜单
    await queryInterface.bulkInsert('menus', [
      {
        id: companyMenuId,
        tenant_id: null,
        parent_id: systemId,
        name: 'company',
        title: '公司管理',
        english: 'Company Management',
        type: 'menu',
        path: '/system/company',
        component: 'Company/index',
        icon: 'solar:buildings-2-linear',
        permission: 'company:read',
        order_num: 5,
        visible: true,
        status: true,
        cache: true,
        redirect: null,
        created_at: now,
        updated_at: now,
      },
      {
        id: departmentMenuId,
        tenant_id: null,
        parent_id: systemId,
        name: 'department',
        title: '部门管理',
        english: 'Department Management',
        type: 'menu',
        path: '/system/department',
        component: 'Department/index',
        icon: 'solar:case-round-linear',
        permission: 'department:read',
        order_num: 6,
        visible: true,
        status: true,
        cache: true,
        redirect: null,
        created_at: now,
        updated_at: now,
      },
    ]);

    console.log('✅ 组织架构菜单添加成功');
    console.log('   - 公司管理');
    console.log('   - 部门管理');
  },

  down: async (queryInterface) => {
    await queryInterface.bulkDelete('menus', {
      name: ['company', 'department']
    }, {});
  }
};

